<template>
	<view>
		<view class="uni-header">
			<uni-stat-breadcrumb class="uni-stat-breadcrumb-on-phone" />
			<view class="uni-group">
				<button class="uni-button" type="primary" size="mini"
					@click="navigateTo('./add')">{{ $t('common.button.add') }}</button>
				<button class="uni-button" type="warn" size="mini" :disabled="!selectedIndexs.length"
					@click="delTable">{{ $t('common.button.batchDelete') }}</button>
				<input class="uni-search" type="text" v-model="query" @confirm="search"
					:placeholder="$t('common.placeholder.query')" />
				<button class="uni-button hide-on-phone" type="default" size="mini"
					@click="search">{{ $t('common.button.search') }}</button>
				<!-- 导入文件 -->
				<button class="uni-button" type="primary" @click="chooseFile" size="mini">导入</button>
				<download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData"
					:type="exportExcel.type" :name="exportExcel.filename">
					<button class="uni-button" type="primary" size="mini">{{$t('common.button.exportExcel')}}</button>
				</download-excel>
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" :collection="collectionList" :options="options" :where="where" page-data="replace"
				:orderby="dbOrderBy" :getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent"
				v-slot:default="{ data, pagination, loading, error, options }" @load="onqueryload">
				<uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe
					type="selection" @selection-change="selectionChange">
					<uni-tr>
						<uni-th align="center" width="50">序号</uni-th>
						<uni-th align="center" width="150">货品编码</uni-th>
						<!-- <uni-th align="center" width="100">供应商</uni-th> -->
						<uni-th align="center" width="220">货品名称</uni-th>
						<uni-th align="center" width="100">规格型号</uni-th>
						<uni-th align="center" width="100">计量单位</uni-th>
						<uni-th align="center" width="100">实际库存</uni-th>
						<uni-th align="center" width="220">产品中文描述</uni-th>
						<uni-th align="center" width="120">货位</uni-th>
						<uni-th align="center" width="80">成本单价</uni-th>
						<uni-th align="center" width="100">未清洗</uni-th>
						<uni-th align="center" width="100">已清洗</uni-th>
						<uni-th align="center" width="100">总库存</uni-th>
						<uni-th align="center" width="80">附件</uni-th>
						<uni-th align="center" width="180">添加时间</uni-th>
						<uni-th align="center" width="180">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item, index) in data" :key="index">
						<uni-td align="center">{{ index + 1 }}</uni-td>
						<uni-td align="center">{{ item.goods_sn }}</uni-td>
						<uni-td align="center">{{ item.name }}</uni-td>
						<uni-td align="center">{{ item.type }}</uni-td>
						<uni-td align="center">{{ item.danwei }}</uni-td>
						<uni-td align="center">{{ item.sj_count || 0 }}</uni-td>
						<uni-td align="center">{{ item.goods_desc }}</uni-td>
						<uni-td align="center">{{ item.position }}</uni-td>
						<uni-td align="center">{{ item.price || 0 }}</uni-td>
						<uni-td align="center">{{ item.yqx_count || 0 }}</uni-td>
						<uni-td align="center">{{ item.wqx_count || 0 }}</uni-td>
						<uni-td align="center">{{ item.remain_count || 0 }}</uni-td>
						<uni-td align="center"><text class="blue cu_po"
								@click="openFj(item.goods_fj)">查看附件</text></uni-td>
						<uni-td align="center">{{ $formatDate(item.add_date) }}</uni-td>
						<uni-td align="center">
							<view class="uni-group">
								<text class="green cu_po" @click="open(item)">+库存</text>

								<text class="blue cu_po" style="margin-left: 5px;"
									@click="navigateTo('./add?id=' + item._id, false)">修改</text>
								<text class="red cu_po" style="margin-left: 5px;"
									@click="confirmDelete(item._id)">删除</text>


							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box">
					<uni-pagination show-icon  :page-size="pagination.size" v-model="pagination.current"
						:total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>

		</view>
		<view class="text-center dialog">
			<!-- 输入框示例 -->
			<uni-popup ref="popup" type="dialog" :mask-click="false">
				<view class="popup-all bg-w">
					<view>
						<view class="" style="display:flex;margin-bottom: 15px;">
							<text>单价：</text> <input class="uni-input" v-model="priceArr.price" type="number"
								placeholder="请输入单价" />
						</view>
						<view class="" style="display:flex">
							<text>数量：</text><input class="uni-input" v-model="priceArr.num" type="number"
								placeholder="请输入数量" />
						</view>
					</view>
					<view class="t-c mar-t-15 ">
						<button class="mini-btn mar-r-15" type="primary" @click="dialogInputConfirm"
							size="mini">确定</button>
						<button class="mini-btn" @click="close" type="default" size="mini">取消</button>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	import * as XLSX from 'xlsx'
	//库存列表
	const db = uniCloud.database();
	const dbCollectionName = 'opendb-mall-goods';
	// 表查询配置
	const dbOrderBy = 'add_date desc'; // 排序字段
	const dbSearchFields = ['goods_sn', 'seller_note', 'keywords','name','goods_desc']; // 支持模糊搜索的字段列表
	// 分页配置
	const pageSize = 10;
	const pageCurrent = 1;

	export default {
		data() {
			return {
				collectionList:"opendb-mall-goods",
				selectedIndexs: [],
				query: '',
				where: '',
				dbOrderBy: dbOrderBy,
				exportExcelData: [],
				exportExcel: {
					"filename": "货品.xls",
					"type": "xls",
					"fields": {
						"货品编码": "goods_sn",
						"货品名称": "name",
						"规格型号": "type",
						"成本单价": "price",
						"货位": "position",
						"帐面库存": "zm_count",
						"实际库存": "sj_count",
						"产品中文描述": "goods_desc",
						"未清洗": "wqx_count",
						"已清洗": "yqx_count",
						"总库存": "remain_count",
					}
				},
				options: {
					pageSize,
					pageCurrent
				},
				cheRow: {},
				priceArr: {},
				columns: [{
						label: 'Name',
						key: 'name'
					},
					{
						label: 'Age',
						key: 'age'
					},
					{
						label: 'Gender',
						key: 'gender'
					}
				],
				tableData: [] // 存储导入的数据
			};
		},
		onLoad() {},
		methods: {
			onqueryload(data) {

				this.exportExcelData = data
			},
			close() {
				this.$refs.popup.close()
			},
			// 增加库存
			async dialogInputConfirm() {
				let data = await db.collection('opendb-mall-goods').doc(this.cheRow._id).field('remain_count').get()
				console.log(this.cheRow.price, this.priceArr.price);
				let nowPrice = (this.cheRow.price + this.priceArr.price * 1) / 2
				let num = data.result.data[0].remain_count + this.priceArr.num * 1

				db.collection('opendb-mall-goods').doc(this.cheRow._id).update({
						price: nowPrice,
						remain_count: num,
						all_price: (nowPrice * num).toFixed(2) * 1
					}).then(res => {
						uni.showToast({
							icon: 'none',
							title: '修改成功'
						});
						this.close();
						this.loadData();
					})
					.catch(err => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						});
					});
			},
			// 创建一个下载多个附件的函数
			downloadMultipleFiles(fileUrls) {
				fileUrls.forEach(function(url, index) {
					setTimeout(function() {
						const a = document.createElement('a');
						a.href = url;
						a.download = ''; // 触发下载并使用默认的文件名
						a.style.display = 'none'; // 隐藏元素
						document.body.appendChild(a);
						a.click(); // 模拟点击下载
						document.body.removeChild(a); // 移除元素
					}, index * 1000); // 每个下载请求间隔 1 秒
				});
			},
			//下载附件
			openFj(item) {
				let url = []
				item.forEach(res => {
					url.push(res.url)
				})
				this.downloadMultipleFiles(url)
			},
			open(e) {
				this.cheRow = e
				this.priceArr = {}
				// 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
				this.$refs.popup.open('center')
			},
			chooseFile() {
				// 调用文件选择器
				uni.chooseFile({
					extension: ['.xlsx', '.xls'],
					success: (res) => {
						const file = res.tempFiles[0];
						console.log(res, 111);
						this.readExcel(file);
					}
				});
			},
			readExcel(file) {
				const reader = new FileReader();
				reader.onload = (e) => {
					const binaryString = e.target.result;
					const wb = XLSX.read(binaryString, {
						type: 'binary'
					});
					const ws = wb.Sheets[wb.SheetNames[0]];
					const data = XLSX.utils.sheet_to_json(ws);
					// 处理并存储数据
					this.tableData = data.map(item => ({
						goods_sn: item['goods_sn'],
						name: item['name'],
						type: item['type'],
						sj_count: item['sj_count'],
						zm_count: item['zm_count'],
						goods_desc: item['goods_desc'],
						position: item['position'],
						price: item['price'],
						yqx_count: item['yqx_count'],
						wqx_count: item['wqx_count'],
						remain_count: item['remain_count'],
					}));
					console.log(this.tableData, 99);
					this.tableData = this.tableData.slice(1)
					uni.showLoading({
						title: '正在添加数据'
					});

					const promises = this.tableData.map(item => {
						return db.collection(dbCollectionName).add({
							goods_sn: item['goods_sn'],
							name: item['name'],
							type: item['type'].toString(),
							sj_count: item['sj_count'],
							zm_count: item['zm_count'],
							goods_desc: item['goods_desc'],
							position: item['position'],
							price: item['price'],
							yqx_count: item['yqx_count'],
							wqx_count: item['wqx_count'],
							remain_count: item['remain_count'],
							add_date: Date.now(),
							unit_id: "6476e69209e2989198d4db61",
							all_price: (item['price'] * item['remain_count']).toFixed(2) * 1
						});
					});

					Promise.all(promises)
						.then(responses => {
							uni.showToast({
								title: '新增成功',
							});

							// 通过 eventChannel 发送 'refreshData' 事件，通知其他页面刷新数据
							this.getOpenerEventChannel().emit('refreshData');

							setTimeout(() => uni.navigateBack(), 500);
						})
						.catch(err => {
							uni.showModal({
								content: err.message || '请求服务失败',
								showCancel: false
							});
						})
						.finally(() => {
							uni.hideLoading();
						});
				};


				reader.readAsBinaryString(file);
			},
			getWhere() {
				const query = this.query.trim();
				if (!query) {
					return '';
				}
				let queryRe;
				try {
					queryRe = new RegExp(query, 'i');
				} catch (err) {
					uni.showToast({
						title: '请勿输入\等不满足正则格式的符号',
						icon: 'none'
					});
					return;
				}
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ');
			},
			search() {
				const newWhere = this.getWhere();
				const isSameWhere = newWhere === this.where;
				this.where = newWhere;
				if (isSameWhere) {
					// 相同条件时，手动强制刷新
					this.loadData();
				}
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				});
			},
			onPageChanged(e) {
				this.selectedIndexs.length = 0;
				this.$refs.table.clearSelection();
				this.$refs.udb.loadData({
					current: e.current
				});
			},
			navigateTo(url) {
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData();
						}
					}
				});
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList;
				console.log(dataList);
				return this.selectedIndexs.map(i => dataList[i]._id);
			},
			// 批量删除
			delTable() {
				this.$refs.udb.remove(this.selectedItems(), {
					success: res => {
						this.$refs.table.clearSelection();
					}
				});
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index;
			},
			confirmDelete(id) {
				this.$refs.udb.remove(id, {
					success: res => {
						this.$refs.table.clearSelection();
					}
				});
			}
		}
	};
</script>
<style>
	.uni-table-tr {

		& th:last-child,
		& td:last-child {
			background-color: white;
		}
	}

	.popup-all {
		padding: 15px
	}
	
</style>